package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

//        排除登录的操作
        String path = request.getURI().getPath(); //  "/login/in"

        if(path.contains("/login")){
//            应该直接放行
            return chain.filter(exchange);
        }


//        从请求头中获取token
        String token = request.getHeaders().getFirst("token");
//        判断请求头中是否有token 如果没有 直接返回401
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int type = AppJwtUtil.verifyToken(claimsBody); //校验token是否有效  -1：有效，0：有效
            if(type==-1 ||type==0){
    //        从token中解析出userId
    //            claimMaps.put("userId",one.getId());
    //            claimMaps.put("name",one.getName());
                Integer userId = claimsBody.get("userId", Integer.class);
                String name = claimsBody.get("name", String.class);

//                向后面的微服务中发送userId（放到请求头中）
                request.mutate().header("userId",userId.toString());
                request.mutate().header("name",name);
                return chain.filter(exchange); //向后面的微服中发送请求
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0; //值越小 越先执行
    }
}
